import sys

from PySide6.QtWidgets import (
    QApplication,
    QMainWindow,
    QTableView
)
from PySide6.QtCore import QSize
from PySide6.QtSql import QSqlDatabase, QSqlQueryModel, QSqlQuery, QSqlQueryModel

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Python")

        self.table = QTableView()
        self.setMinimumSize(QSize(1024, 600))
        self.setCentralWidget(self.table)

        if self.initDb():
            self.model = QSqlQueryModel()
            self.table.setModel(self.model)
            # query = QSqlQuery("SELECT NAME, Composer FROM Track ", db=self.db)
            query = QSqlQuery(db=self.db)
            query.prepare("SELECT Name, Composer, Album.Title From Track "
                          " INNER JOIN Album ON Track.AlbumId = Album.AlbumId"
                          " WHERE Album.Title LIKE '%' || :album_title || '%' "
                          )
            query.bindValue(":album_title", "Sinatra")
            query.exec()
            
            self.model.setQuery(query)

    def initDb(self):
        self.db = QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("Chinook_Sqlite.sqlite")

        if not self.db.open():
            print("Connot not open database")
            return False

        return True
    
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

